//
//  TLChatViewController.m
//  TLMessageView
//
//  Created by 郭锐 on 16/8/18.
//  Copyright © 2016年 com.garry.message. All rights reserved.
//

#import "TLChatViewController.h"
#import "TLProjectMacro.h"
#import "TLTextMessageCell.h"
#import "TLPhotoMessageCell.h"
#import "TLChatInputView.h"
#import "MessageModel.h"
#import "IGImMsgDetailApi.h"
#import "IGSendMsgApi.h"
#import "IGOSSManager.h"

@interface TLChatViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) TLChatInputView *inputView;
@property (nonatomic, strong) NSMutableArray *messages;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) IGImMsgDetailApi *msgDetaiApi;
@property (nonatomic, assign) NSInteger pageNumber;
@property (nonatomic, copy) NSString *lastTimeDate;
@property (nonatomic, copy) NSString *uid;
@property (nonatomic, strong) IGSendMsgApi *sendMsgApi;

@end

@implementation TLChatViewController

-(NSMutableArray *)messages{
    if (!_messages) {
        _messages=[NSMutableArray array];
    }
    return _messages;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    AdjustsScrollViewInsetNever(self, self.chatTableView);
    
    self.chatTableView.backgroundColor=[UIColor c2Color];
    [self.view addSubview:self.inputView];
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
        make.height.mas_offset(@45);
    }];
    
    [self.view addSubview:self.chatTableView];
    [self.chatTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.top.equalTo(self.mas_topLayoutGuideBottom).offset(0);
        make.bottom.equalTo(self.inputView.mas_top).offset(0);
    }];
    
    __weak typeof(self) weakSelf = self;
    //发送消息回调
    self.inputView.sendMsgAction = ^(NSString *x){
        [weakSelf sendSixinMessage:x withMessageType:@"1"];
    };
    
    self.inputView.sendImageAction = ^(UIImage *image){
        [weakSelf sendImageWithImage:image];
    };
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshNewMessageList:) name:@"siMessageNotificationKey" object:nil];
    _pageNumber = 1;
    _lastTimeDate = @"";
    
    [[IGOSSManager sharedManager] requestOssToken:IGAliYunFolderTypeSiXin];

    self.sendMsgApi = [IGSendMsgApi new];
    self.msgDetaiApi = [IGImMsgDetailApi new];
    [self requestData];
    [self.chatTableView ig_setHeaderWithRefreshingBlock:^{
        weakSelf.pageNumber++;
        [weakSelf requestData];
    }];
}

- (void)dealloc {
    
}

// 当推送来消息的时候刷新到最新消息
- (void)refreshNewMessageList:(NSNotification *)notification {
    _pageNumber = 1;
    _lastTimeDate = @"";
    [self requestData];
}

- (void)requestData{
    _msgDetaiApi.lastTimeDate = _lastTimeDate;
    _msgDetaiApi.pageNum = _pageNumber;
    _msgDetaiApi.senderId = _otherId;
    @KWeakObj(self)
    [self.msgDetaiApi startWithDecodeClass:[IGImMsgDetailResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [selfWeak.chatTableView ig_endHeaderRefreshing];
        [selfWeak.chatTableView ig_endFooterRefreshing];
        if(responseObject){
            IGImMsgDetailResp *resp=responseObject;
            IGImMsgDetailModel *model=resp.data;
            NSArray *tmpArr = model.msgs;
            
            if (tmpArr && tmpArr.count>0) {
                selfWeak.lastTimeDate = model.lastTimeDate;
            }
            if (selfWeak.pageNumber == 1) {
                //把ImMsgDetail转化为MessageModel
                selfWeak.messages = [NSMutableArray array];
                for (int i = 0; i < tmpArr.count; i++) {
                    ImMsgDetail *msgDetail = [tmpArr objectAtIndex:i];
                    MessageModel *messageModel = [MessageModel convertFrom:msgDetail];
                    [selfWeak.messages addObject:messageModel];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [selfWeak scrollToBottom]; 
                });
            } else {
                //把ImMsgDetail转化为MessageModel
                for (NSInteger i = tmpArr.count - 1; i >= 0; i--) {
                    ImMsgDetail *msgDetail = [tmpArr objectAtIndex:i];
                    MessageModel *messageModel = [MessageModel convertFrom:msgDetail];
                    [selfWeak.messages insertObject:messageModel atIndex:0];
                }
            }
            [selfWeak.chatTableView reloadData];
        } else {
            //空白页处理逻辑写在这里
        }
    }];
}

- (void)scrollToBottom {
    if (self.messages.count) {
        [self.chatTableView scrollToRowAtIndexPath:[self lastMessageIndexPath] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

#pragma mark -----发送私信
- (void)postPersonalMessage:(NSString *)messageContent messageType:(NSString *)messageType
{
    
}

#pragma - mark tableviewDelegate

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageModel *messageModel = _messages[indexPath.row];
    
    NSString *cellIdentifier;
    if (messageModel.type == 1) {//文本加表情
        cellIdentifier = @"textcell";
    }else{//图片
        cellIdentifier = @"photocell";
    }
    
    TLMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    __weak typeof(self) weakSelf = self;
    cell.reSendAction = ^(MessageModel *msg){
        msg.messageStatus = MessageStatus_SENDING;
        [weakSelf retrySendMessage:msg];
    };
    
    MessageModel *lastMessageModel = [self lasetMsgWithIndex:indexPath.row];
    BOOL showDate = (messageModel.created_at - lastMessageModel.created_at) > 60 * 5;
    [cell updateMessage:messageModel showDate:showDate];
    
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.messages.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageModel *messageModel = self.messages[indexPath.row];
    MessageModel *lastMessageModel = [self lasetMsgWithIndex:indexPath.row];
    
    NSString *cellIdentifier;
    if (messageModel.type == 1) {
        cellIdentifier = @"textcell";
    }else{
        cellIdentifier = @"photocell";
    }
    
    CGFloat height = [tableView fd_heightForCellWithIdentifier:cellIdentifier cacheByIndexPath:indexPath configuration:^(TLMessageCell *cell) {
        BOOL showDate = (messageModel.created_at - lastMessageModel.created_at) > 60 * 5;
        [cell updateMessage:messageModel showDate:showDate];
    }];
    if (messageModel.type != 1) {
        return 166;
    }
    return height;
}

#pragma - mark RCManagerDelegate

-(void)rcManagerReceiveMsg:(MessageModel *)msg{
    msg.messageStatus = MessageStatus_RECEIVED;
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf insertMessage:msg];
    });
}

#pragma - mark private
-(void)sendSixinMessage:(NSString *)content withMessageType:(NSString *)messageType{
    MessageModel *messageModel = [[MessageModel alloc] init];
    messageModel.title = content;
    messageModel.messageType = MessageType_SEND;
    messageModel.u_id = [IGUser getUid];
    messageModel.n_id = _otherId;
    messageModel.type = [messageType integerValue];
    if ([messageType integerValue] == 2) {
        messageModel.imgSmall = content;
    }
    messageModel.created_at = [NSDate timeStamp];
    messageModel.messageStatus = MessageStatus_SENDING;
    messageModel.image = [IGUser getImage];
    [self insertMessage:messageModel];
    [self.chatTableView reloadData];
    
    [self sendMessage:messageModel];
}

- (void)sendMessage:(MessageModel *)messageModel {
    self.sendMsgApi.messageModel = messageModel;
    __weak typeof(self) weakSelf = self;
    [self.sendMsgApi startWithDecodeClass:[IGSendMsgResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            messageModel.messageStatus = MessageStatus_SENT;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.chatTableView reloadData];
            });
        } else {
            messageModel.messageStatus = MessageStatus_FAILED;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.chatTableView reloadData];
            });
        }
    }];
}

#pragma mark - 上传图片 然后发送
- (void)sendImageWithImage:(UIImage *)image {
    [self.view endEditing:YES];
//    [self showText:@"正在发送..."];
    [self showText:NSLocalizedString(@"Sending...", nil)];
    __weak typeof(self) weakSelf = self;
    [[IGOSSManager sharedManager] asyncPutImages:@[image] withCompleteBlock:^(NSArray *params, NSArray *urls) {
        if (params.count != 0) {
            [weakSelf sendSixinMessage:params.firstObject withMessageType:@"2"];
            [weakSelf dismissLoading];
        } else {
//            [weakSelf presentMessageTips:@"发送失败"];
            [weakSelf presentMessageTips:NSLocalizedString(@"Sending Failed", nil)];
        }
    }];
}

- (void)insertMessage:(MessageModel *)message{
    if (!message.title) {
        return;
    }
    [self.messages addObject:message];
    
    [self.chatTableView insertRowsAtIndexPaths:@[[self lastMessageIndexPath]] withRowAnimation:UITableViewRowAnimationFade];
    
    [self.chatTableView scrollToRowAtIndexPath:[self lastMessageIndexPath] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (void)retrySendMessage:(MessageModel *)message{
    [self sendMessage:message];
}

-(void)updateCellStatusWithMsg:(MessageModel *)msg{
    NSInteger index = [self.messages indexOfObject:msg];
    TLMessageCell *cell = [self.chatTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [cell setMsgStatus:msg.messageStatus];
}

-(NSIndexPath *)lastMessageIndexPath{
    return [NSIndexPath indexPathForItem:self.messages.count - 1 inSection:0];
}
-(MessageModel *)lasetMsgWithIndex:(NSInteger)index{
    return index > 0 ? self.messages[index - 1] : nil;
}

#pragma - mark getter
-(UITableView *)chatTableView{
    if (!_chatTableView) {
        _chatTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _chatTableView.delegate = self;
        _chatTableView.dataSource = self;
        _chatTableView.backgroundColor = UIColorFromRGB(0xebebeb);
        _chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _chatTableView.backgroundColor = UIColorFromRGB(0xf8f8f8);
        _chatTableView.separatorColor = UIColorFromRGB(0xeeeeee);
        if (@available(iOS 11.0, *)) {
            _chatTableView.estimatedRowHeight = 0;
            _chatTableView.estimatedSectionHeaderHeight = 0;
            _chatTableView.estimatedSectionFooterHeight = 0;
            _chatTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        [_chatTableView registerClass:[TLTextMessageCell class] forCellReuseIdentifier:@"textcell"];
        [_chatTableView registerClass:[TLPhotoMessageCell class] forCellReuseIdentifier:@"photocell"];
    }
    return _chatTableView;
}
-(TLChatInputView *)inputView{
    if (!_inputView) {
        _inputView = [[TLChatInputView alloc] initWithChatVc:self];
    }
    return _inputView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
